<template>
  <div class="file-upload">
    <div class="upload-box" :class="{'is-dragover':drag && isDragOverRef}" v-on="events">
      <slot v-if="isUploading" name="loading">
        <button disabled>正在上传</button>
      </slot>
      <slot v-else-if="lastFileData && lastFileData.uploaded" name="uploaded" :uploadedData="lastFileData.data">
        <button>点击上传</button>
      </slot>
      <slot v-else name="default">
        <button>点击上传</button>
      </slot>
    </div>

    <input
        ref="fileInputRef"
        type="file"
        :style="{display:'none'}"
        @change="handleFileChange"
    />
    <ul class="upload-list" :class="`upload-list-${listType}`" v-if="showList">
      <li class="upload-item" :class="`uploaded-file upload-${file.status}`" v-for="file in filesListRef"
          :key="file.uid">
        <img class="upload-list-thumbnail" :src="file.url" :alt="file.name" v-if="listType==='picture' && file.url"/>
        <span v-if="file.status === 'loading'" class="file-icon"><LoadingOutlined/></span>
        <span v-else class="file-icon"><FileOutlined/></span>
        <span class="file-name">{{ file.name }}</span>
        <span class="delete-icon" @click="removeFile(file.uid)"><DeleteOutlined/></span>
      </li>
    </ul>
  </div>
</template>

<script lang='ts'>
import { defineComponent, onMounted, ref, reactive, computed, PropType } from 'vue'
import { DeleteOutlined, LoadingOutlined, FileAddOutlined } from '@ant-design/icons-vue'
import axios, { AxiosResponse } from 'axios'
import { v4 as uuidV4 } from 'uuid'
import { clone, last } from 'lodash-es'
import { UploadResp } from '../../extraType'

// 成功上传回调数据接口
export interface SuccessData {
  resp: UploadResp;
  file: File;
}

type UploadStatus = 'ready' | 'loading' | 'success' | 'error' // 上传状态字面类型
type CheckUpload = (file: File) => Promise<File> | boolean  // 验证上传的函数类型
type SuccessUpload = (data: SuccessData) => void  // 成功上传后的函数类型
type ListType = 'picture' | 'text' // 上传列表支持的两种类型 picture 图片（支持预览） text 文字类型
// 上传文件的类型
export interface UploadFile {
  uid: string;  // 唯一标识
  name: string; // 文件名称
  size: number; // 文件大小
  status: UploadStatus; // 上传状态
  raw: File; // 文件本身
  resp?: any; // 上传完成后，服务器返回的数据
  url?: string; // 展示缩略图的 url
}

// 上传后的返回数据类型
export interface LoadedData {
  uploaded: boolean;
  data: any;
}

export default defineComponent({
  components: {
    DeleteOutlined,
    LoadingOutlined,
  },
  props: {
    action: {
      type: String,
      required: true
    },
    drag: {
      type: Boolean, // 是否支持拖动文件上传，默认 false
      default: false
    },
    autoUpload: {
      type: Boolean, // 是否自动上传文件，默认 true
      default: true
    },
    beforeUpload: {
      type: Function as PropType<CheckUpload>
    },
    // 成功上传后的钩子函数
    onSuccess: {
      type: Function as PropType<SuccessUpload>
    },
    listType: {
      type: String as PropType<ListType>,
      default: 'text' // 列表类型 picture 支持展示缩略图  text 默认 不展示缩略图
    },
    showList: {
      type: Boolean,
      default: true  // 默认展示上传列表
    }
  },
  setup(props) {
    // ref 可以获取 DOM 元素  通过元素的 ref 属性
    const fileInputRef = ref<null | HTMLInputElement>(null)
    // 上传文件列表
    const filesListRef = ref<UploadFile[]>([])
    // 点击上传按钮
    const triggerUpload = (e: Event) => {
      if (fileInputRef.value) {
        fileInputRef.value.click()
      }
    }
    // 事件列表对象 可通过 v-on 绑定多个事件
    let events: { [key: string]: (e: any) => void } = {
      click: triggerUpload
    }
    // 上传状态  ready 初始上传前 | loading 正在上传 | success | 上传成功 | error 上传出错啦
    // 是否正在上传，只要有一个文件在上传那，按钮就显示 正在上传
    const isUploading = computed(() => {
      return filesListRef.value.some(file => file.status === 'loading')
    })
    const removeFile = (uid: string) => {
      filesListRef.value = filesListRef.value.filter(file => file.uid !== uid)
    }
    // 最后一个上传完成的返回数据，如果有则展示对应数据
    const lastFileData = computed<LoadedData | boolean>(() => {
      const lastFile = last(filesListRef.value) as UploadFile
      if (lastFile) {
        console.log(lastFile.resp.data.url)
        return {
          uploaded: lastFile.status === 'success',
          data: lastFile.resp.data
        }
      }
      return false
    })


    // 发送上传请求
    const postFile = (fileObj: UploadFile) => {
      const formData = new FormData() // FormData 接口提供了一种表示表单数据的键值
      formData.append(fileObj.name, fileObj.raw)
      fileObj.status = 'loading'
      // console.log('formData', formData.getAll(uploadFile.name))
      axios.post(props.action, formData, {
        headers: {
          'Content-Type': 'multipart/form-data' // 图片文件需二进制格式发送
        }
      }).then(resp => {
        const respData = resp.data as UploadResp
        fileObj.status = 'success'
        fileObj.resp = respData
        if (props.onSuccess) {
          props.onSuccess({ resp: respData, file: fileObj.raw })
        }
      }).catch(error => {
        console.error(error.message)
        fileObj.status = 'error'
      }).finally(() => {
        if (fileInputRef.value) {
          fileInputRef.value.value = ''
        }
      })
    }

    // 添加一个文件到上传列表
    const addUploadFileToList = (readyFile: File) => {
      const fileObj = reactive<UploadFile>({
        uid: uuidV4(),
        name: readyFile.name,
        size: readyFile.size, // 默认是ready状态 支持手动上传
        status: 'ready',
        raw: readyFile,
      })
      // 如果上传的文件是图片则展示缩略图
      console.log(readyFile.type.substr(0, 5))
      if (props.listType === 'picture' && readyFile.type.substr(0, 5) === 'image') {
        // 方式一： 使用 URL静态方法createObjectURL
        try {
          fileObj.url = URL.createObjectURL(readyFile)
        } catch (err) {
          console.error('upload file error', err)
        }
        // 方式二： FileReader对象的readAsDataURL方法 展示 base64 缩略图
        // const fileReader = new FileReader()
        // fileReader.readAsDataURL(readyFile)
        // fileReader.addEventListener('load', () => {
        //   fileObj.url = fileReader.result as string
        // })
      }
      filesListRef.value.push(fileObj)
      // 自动上传
      if (props.autoUpload) {
        postFile(fileObj)
      }
    }

    // 上传前检查
    const beforeUploadCheck = (files: FileList | null) => {
      if (files) {
        // 拿到要上传的 File对象 https://developer.mozilla.org/zh-CN/docs/Web/API/File
        const uploadFile = files[0]
        if (props.beforeUpload) { // 如果有 beforeUpload
          const result = props.beforeUpload(uploadFile) // 执行 beforeUpload
          if (result && result instanceof Promise) {  // 如果执行结果是 Promise ，上传处理后的 file
            result.then(processedFile => {
              if (processedFile instanceof File) {  // Promise 返回的类型必须是 File
                addUploadFileToList(processedFile)
              } else {
                throw new Error('beforeUpload Promise should return File object')
              }
            }).catch(e => {
              console.error(e)
            })
          } else if (result === true) {  // 如果结果是 true
            addUploadFileToList(uploadFile)
          }
        } else {
          addUploadFileToList(uploadFile)
        }
      }
    }
    // 是否拖拽文件到区域内
    const isDragOverRef = ref<boolean>(false)
    // 点击上传按钮触发
    const handleFileChange = (e: Event) => {
      const target = e.target as HTMLInputElement
      // 获取 Filelist（array-like object伪数组）
      // https://developer.mozilla.org/zh-CN/docs/Web/API/FileList
      beforeUploadCheck(target.files)
    }

    // 拖动文件时触发，over 是否拖动到区域内
    const handleDrag = (e: DragEvent, over: boolean) => {
      e.preventDefault() // 去除默认行为（拖动到浏览器tab打开等）
      isDragOverRef.value = over
    }
    // 拖动松开时触发
    const handleDrop = (e: DragEvent) => {
      e.preventDefault()
      isDragOverRef.value = false
      // 如果松开时 有文件，则触发上传
      // DataTransfer 对象用于保存拖动并放下（drag and drop）过程中的数据
      // https://developer.mozilla.org/zh-CN/docs/Web/API/DataTransfer
      if (e.dataTransfer) {
        // DataTransfer.files -> FileList 对象 ：包含数据传输中可用的所有本地文件的列表。如果拖动操作不涉及拖动文件，则此属性为空列表。
        beforeUploadCheck(e.dataTransfer.files)
      }
    }

    // 上传文件
    const uploadFiles = () => {
      // 将文件列表中所有 ready 的文件上传
      filesListRef.value.filter(file => file.status === 'ready').forEach(readyFile => postFile(readyFile))
    }
    // 如果支持拖动上传，则绑定拖动相关事件
    if (props.drag) {
      events = {
        ...events,
        dragover: (e: DragEvent) => {
          handleDrag(e, true)
        },
        dragleave: (e: DragEvent) => {
          handleDrag(e, false)
        },
        drop: handleDrop
      }
    }

    return {
      triggerUpload,
      fileInputRef,
      isUploading,
      handleFileChange,
      filesListRef,
      removeFile,
      lastFileData,
      events,
      isDragOverRef,
      uploadFiles
    }
  }
})
</script>

<style lang='scss' scoped>
.upload-list {
  margin: 0;
  padding: 0;
  list-style-type: none;
}

.upload-list li {
  transition: all .5s cubic-bezier(.55, 0, .1, 1);
  font-size: 14px;
  line-height: 1.8;
  margin-top: 5px;
  box-sizing: border-box;
  border-radius: 4px;
  min-width: 200px;
  position: relative;

  &:first-child {
    margin-top: 10px;
  }

  .upload-list-thumbnail {
    vertical-align: middle;
    display: inline-block;
    width: 70px;
    height: 70px;
    position: relative;
    z-index: 1;
    background-color: #fff;
    object-fit: cover;
  }

  .file-icon {
    svg {
      margin-right: 5px;
      color: rgba(0, 0, 0, 0.45);
    }
  }

  .file-name {
    margin-left: 5px;
    margin-right: 40px;
  }

  &.upload-error {
    color: #f5222d;

    svg {
      color: #f5222d;
    }
  }

  .file-status {
    display: block;
    position: absolute;
    right: 5px;
    top: 0;
    line-height: inherit;
  }

  .delete-icon {
    display: none;
    position: absolute;
    right: 7px;
    top: 0;
    line-height: inherit;
    cursor: pointer;
  }

  &:hover {
    background-color: #efefef;

    .file-status {
      display: none;
    }

    .delete-icon {
      display: block;
    }
  }
}
</style>